package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func createDirIfNotExist(path string) error {
	dir := path[:strings.LastIndex(path, "/")]
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		if err = os.MkdirAll(dir, os.ModePerm); err != nil {
			return err
		}
	}
	return nil
}

func downloadFile(url string, filepath string) error {
	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)

	// Create the file
	err = createDirIfNotExist(filepath)
	if err != nil {
		return err
	}
	out, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer func(out *os.File) {
		_ = out.Close()
	}(out)

	// Write the body to file
	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return err
	}

	fmt.Println("Downloaded file: ", filepath)
	return nil
}

func downloadFileFormFileServer() {
	url := "http://127.0.0.1:10121/scripts/download/prometheus-op.sh"
	filepath := "./home/prometheus-op.sh"
	err := downloadFile(url, filepath)
	if err != nil {
		fmt.Println("Error downloading file: ", err)
	}
}
